﻿using System;
using System.IO;
using FFmpegVideoClip.Lib;

namespace MediaInfoLib
{
    public class MediaInfoTools
    {
        public static TimeSpan GetDuration(string FilePath)
        {
            if (!File.Exists(FilePath))
                throw new FileNotFoundException($"{FilePath} 文件不存在");

            using (MediaInfo mi = new())
            {
                mi.Open(FilePath);
                string? duration = mi.Get(StreamKind.General, 0, GeneralQueryItems.Duration);
                if (string.IsNullOrEmpty(duration) || !double.TryParse(duration, out double durationValue))
                    throw new MediaInfoException("获取[Duration]失败");
                return TimeSpan.FromMilliseconds(durationValue);
            }
        }

        public static bool IsGetDuration(string FilePath, out TimeSpan Result)
        {
            Result = TimeSpan.Zero;
            GetMediaInfo.MediaInfoResult Info = GetMediaInfo.GetInfo(FilePath);
            if(Info.HasDuration)
            {
                Result = Info.Duration;
                return true;
            }
            return false;
        }

        

        [Serializable]
        public class MediaInfoException : Exception
        {
            public MediaInfoException() { }
            public MediaInfoException(string message) : base(message) { }
            public MediaInfoException(string message, Exception inner) : base(message, inner) { }
            [Obsolete]protected MediaInfoException(
              System.Runtime.Serialization.SerializationInfo info,
              System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
        }
    }
}
